package com.hooker.penetration

import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hooker.adapter.RuleListAdapter
import com.hooker.hook.Rule
import com.hooker.settings.Setting
import com.hooker.settings.SettingHelper
import com.hooker.util.Constants
import com.sdk.hooker.penetration.R


class RuleListActivity : AppCompatActivity() {

    private lateinit var recyclerView: RecyclerView
    lateinit var adapter: RuleListAdapter
    lateinit var emptyView: TextView
    var list: MutableList<Rule> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rule_list)
        initView()
        initData()
    }

    private fun initView() {
        recyclerView = findViewById(R.id.recyclerView)
        recyclerView?.overScrollMode = View.OVER_SCROLL_NEVER
        emptyView = findViewById(R.id.empty)
    }

    private fun initData() {
        getDataFromLocal()
        adapter = RuleListAdapter(this, list, recyclerView!!)
        adapter.setOnItemClickListener(object : RuleListAdapter.OnItemClickListener {
            override fun onClick(view: View, position: Int) {
//                adapter.notifyDataSetChanged()
                when (view.id) {
                    R.id.btn_rule_delete -> {
                        SettingHelper.removeInfo(
                            this@RuleListActivity,
                            Constants.RULE_TAG_ID,
                            list[position].toString()
                        )
                        list.removeAt(position)
                        adapter.notifyDataSetChanged()
                        updateView()
                    }
                    else -> {

                    }
                }
            }
        })
        recyclerView?.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        recyclerView?.adapter = adapter
    }

    /**
     * 获取hook名
     */
    private fun getDataFromLocal() {
        list.clear()
        var set: List<String> = SettingHelper.getInfo(this, Constants.RULE_TAG_ID)

        for (s in set) {
            val rule = Gson().fromJson<Rule>(s, object : TypeToken<Rule>() {}.type)
            rule?.update()
            if (rule != null) {
                list.add(rule)
            }
        }
        updateView()
    }

    private fun updateView() {
        when (list.size) {
            0 -> {
                emptyView.visibility = View.VISIBLE
                recyclerView.visibility = View.GONE
            }
            else -> {
                emptyView.visibility = View.GONE
                recyclerView.visibility = View.VISIBLE
            }
        }
    }
}
